package com.pay.controller;

import com.baomidou.mybatisplus.core.toolkit.StringUtils;
import com.pay.common.core.api.base.BaseApiController;
import com.pay.common.core.api.base.BaseResponse;
import com.pay.common.pay.utils.RedisUtils;
import com.pay.dto.req.PayMerchantInfoDTO;
import com.pay.entity.PayMerchantInfoDO;
import com.pay.service.Impl.PayMessageTemplateServiceImpl;
import com.pay.service.PayMerchantInfoService;
import io.swagger.annotations.Api;
import io.swagger.annotations.ApiOperation;
import org.springframework.beans.BeanUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.web.bind.annotation.*;

/**
 * <p>
 *  前端控制器
 * </p>
 *
 * @author zhouyihe
 * @since 2024-04-14
 */
@RestController
@RequestMapping("/merchant")
@CrossOrigin
@Api(tags = "用户信息管理")
public class PayMerchantInfoController extends BaseApiController {
    
    @Autowired
    private PayMerchantInfoService payMerchantInfoService;
    
    @Autowired
    private PayMessageTemplateServiceImpl payMessageTemplateServiceImpl;
    
    /**
     * 在数据库中新增商户
     * @param payMerchantInfoDTO
     * @return
     */
    @PostMapping("/merchantSettlement")
    @ApiOperation(value = "在数据库中新增用户",notes = "不能添加socialCreditCode相同的两个用户")
    public BaseResponse<String> merchantSettement(@RequestBody PayMerchantInfoDTO payMerchantInfoDTO){
        // 根据socialCreditCode查询数据库中该数据是否存在
        String socialCreditCode = payMerchantInfoDTO.getSocialCreditCode();
        if (StringUtils.isEmpty(socialCreditCode)) {
            return setResultError("socialCreditCode is null");
        }
        PayMerchantInfoDO payMerchantInfoDb =
                payMerchantInfoService.getBySocialCreditCodePayMerchantInfo(socialCreditCode);
        if (payMerchantInfoDb != null) {
            // 已经提交了该数据无需重复提交数据
            return setResultError("请勿重复提交..");
        }
        // dto与do转换
        PayMerchantInfoDO payMerchantInfoDO =new PayMerchantInfoDO();
        BeanUtils.copyProperties(payMerchantInfoDTO, payMerchantInfoDO);
        
        // 根据token获取对应的openid
        String qrCodeToken = payMerchantInfoDTO.getQrCodeToken();
        if (!StringUtils.isEmpty(qrCodeToken)) {
            payMerchantInfoDO.setContactWxOpenid(RedisUtils.getString(qrCodeToken));
        }
        BeanUtils.copyProperties(payMerchantInfoDTO, payMerchantInfoDO);
        // 判断添加用户是否成功
        boolean addPayMerchantInfoResult = payMerchantInfoService.addPayMerchantInfo(payMerchantInfoDO);
        if (addPayMerchantInfoResult) {
            // 商家提交资料---发送消息模板推送
            payMessageTemplateServiceImpl.notifyMerchantSettlementThread(payMerchantInfoDO);
        }
        return  addPayMerchantInfoResult ? setResultSuccess() : setResultError();
    }
}
